package com.punai.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.punai.common.core.domain.entity.SysUser;
import com.punai.system.domain.CsLinkUserRole;
import com.punai.system.mapper.CsLinkUserRoleMapper;
import com.punai.system.service.CsRoleLinkUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CsRoleLinkUserServiceImpl implements CsRoleLinkUserService {

    @Autowired
    private CsLinkUserRoleMapper csLinkUserRoleMapper;

    @Override
    public List<SysUser> selectLinkUserList(SysUser sysUser) {
        List<SysUser> sysUsers = csLinkUserRoleMapper.selectAllocatedList(sysUser);
        return sysUsers;
    }

    @Override
    @Transactional
    public int insertAuthUsers(String roleId, Long[] userIds, Long companyId) {
        for (Long userId : userIds) {
            CsLinkUserRole ur = new CsLinkUserRole();
            ur.setRoleid(roleId);
            ur.setCompanyId(companyId);
            ur.setUserid(userId);
            csLinkUserRoleMapper.insert(ur);
        }
        return 1;
    }

    @Override
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return csLinkUserRoleMapper.selectUnallocatedList(user);
    }

    @Override
    public int cancelAll(Long roleId, Long[] userIds, Long companyId) {
        return csLinkUserRoleMapper.delete(
                Wrappers.<CsLinkUserRole>lambdaQuery()
                        .eq(CsLinkUserRole::getCompanyId,companyId)
                        .in(CsLinkUserRole::getUserid,userIds)
                        .eq(CsLinkUserRole::getRoleid,roleId)
        );
    }

    @Override
    public int cancel(CsLinkUserRole csLinkUserRole) {
        String roleid = csLinkUserRole.getRoleid();
        Long companyId = csLinkUserRole.getCompanyId();
        Long userid = csLinkUserRole.getUserid();
        return csLinkUserRoleMapper.delete(
                Wrappers.<CsLinkUserRole>lambdaQuery()
                        .eq(CsLinkUserRole::getCompanyId,companyId)
                        .eq(CsLinkUserRole::getUserid,userid)
                        .eq(CsLinkUserRole::getRoleid,roleid)
        );
    }
}
